#include "mqtt_client.h"
#include "platform.h"
int MQTTClient_Connect(MQTT* dev, const char* ip, uint16_t port)
{
	Packet_CONNECT(dev);
	DEBUG_RAW("start connect", dev->write_buf, dev->write_len, dev->MQTT_Connect.Connack_ErrCode);
	mqtt_socket_thread_init(MQTT_CLIENT,dev, ip, port);
	do
	{
		mqtt_sem_wait(dev);
		if (dev->data_err == 1)
		{
			mqtt_sem_post(dev);
			break;
		}
		if (dev->Current_State == CONNACK && dev->MQTT_Connect.Connack_ErrCode == 0)
			break;
	} while (1);
	
	return 1;
}

int MQTTClient_Subscribe(MQTT* dev, const char* SubscribeTpioc)
{
	memcpy(dev->MQTT_Subscribe.SubscribeTpioc, SubscribeTpioc, strlen(SubscribeTpioc));
	Packet_SUBSCRIBE(dev);
	if (dev->send_handle != NULL)
		dev->send_handle(dev);
	do
	{
		mqtt_sem_wait(dev);
		if (dev->data_err == 1)
		{
			mqtt_sem_post(dev);
			break;
		}
		if (dev->Current_State == SUBACK && (dev->MQTT_Subscribe.Subscribe_Result == 0 || dev->MQTT_Subscribe.Subscribe_Result == 1 || dev->MQTT_Subscribe.Subscribe_Result == 2 || dev->MQTT_Subscribe.Subscribe_Result == 128))
		{
			mqtt_sem_post(dev);
			break;
		}
	} while (1);
	return 1;
}